<template>
  <div class="block-list-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchParams" inline>
        <el-form-item label="时间范围">
          <el-date-picker
            ref="datePickerRef"
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>运营日统计列表</span>
        </div>
      </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        stripe
        table-layout="auto"
      >
        <el-table-column prop="reportDate" label="统计日期" min-width="100">
          <template #default="{ row }">
            {{ row?.reportDate ? formatDateTime(row.reportDate) : "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="newUserCount"
          label="新用户注册数"
          min-width="120"
        />
        <el-table-column
          prop="newUserRechargeAmount"
          label="新用户充值金额"
          min-width="120"
        />
        <el-table-column
          prop="dailyRechargeAmount"
          label="日充值金额"
          min-width="120"
        />
        <el-table-column
          prop="dailyRechargeCoin"
          label="日充值金币"
          min-width="120"
        />
        <el-table-column
          prop="newGuildCount"
          label="新公会创建数"
          min-width="120"
        />
        <el-table-column
          prop="activeUserCount"
          label="今日活跃用户数"
          min-width="120"
        />
        <el-table-column
          prop="luckyGiftInputCoin"
          label="幸运礼物投入总金币"
          min-width="120"
        />
        <el-table-column
          prop="luckyGiftReturnCoin"
          label="幸运礼物产出总金币"
          min-width="120"
        />
        <el-table-column
          prop="luckyGiftRoi"
          label="幸运礼物ROI值 (返还/投入)	"
          min-width="120"
        />

        <el-table-column
          prop="remark"
          label="备注"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.remark || "-" }}
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="ReportDailyStatus[row.status]">
              {{ ReportDailyStatusText[row.status] }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElDatePicker, ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Unlock } from "@element-plus/icons-vue";
import {
  ReportDailyStatus,
  ReportDailyStatusText,
  getReportDailyPageApi,
  ReportDailyRecordDto,
  ReportDailySearchReq,
} from "@/api/statist";

// 响应式数据
// 创建ref引用
const datePickerRef = ref<InstanceType<typeof ElDatePicker> | null>(null);
const loading = ref(false);
const tableData = ref<ReportDailyRecordDto[]>([]);
const totals = ref(0);
const dateRange = ref<[string, string] | null>(null);
const now = new Date();
// 创建当前时间前十天的UTC时间0点的日期对象
const tenDaysAgo = new Date(now.getTime() - 10 * 24 * 60 * 60 * 1000);
const startOfDay = new Date(
  Date.UTC(
    tenDaysAgo.getUTCFullYear(),
    tenDaysAgo.getUTCMonth(),
    tenDaysAgo.getUTCDate()
  )
);

// 创建当天UTC时间23:59:59.999的日期对象
const endOfDay = new Date(
  Date.UTC(
    now.getUTCFullYear(),
    now.getUTCMonth(),
    now.getUTCDate(),
    23,
    59,
    59,
    999
  )
);

// 转换为UTC时间
const convertToUTC = (localTime: string) => {
  if (!localTime) return "";
  const date = new Date(localTime);
  return date.toISOString();
};

// 搜索参数
const searchParams = reactive<ReportDailySearchReq>({
  startDate: startOfDay.toISOString(),
  endDate: endOfDay.toISOString(),
  pageIndex: 1,
  pageSize: 10,
});

// 分页参数
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
});

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 处理时间范围
    if (dateRange.value) {
      searchParams.startDate = convertToUTC(dateRange.value[0]);
      searchParams.endDate = convertToUTC(dateRange.value[1]);
    } else {
      // 直接使用toISOString()获取UTC时间格式
      searchParams.startDate = startOfDay.toISOString();
      searchParams.endDate = endOfDay.toISOString();

      // 同时赋值给dateRange.value
      dateRange.value = [startOfDay.toISOString(), endOfDay.toISOString()];

      // 使用nextTick等待DOM更新完成后失焦
      nextTick(() => {
        // 方法1: 通过组件引用获取内部输入框并失焦
        if (datePickerRef.value) {
          (datePickerRef.value as any).handleClose();
        }
      });
    }

    const response = await getReportDailyPageApi(searchParams);
    tableData.value = response.data.list;
    totals.value = response.data.total;
  } catch (error) {
    console.error("加载封禁记录失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchParams.startDate = convertToUTC(startOfDay.toISOString());
  searchParams.endDate = convertToUTC(endOfDay.toISOString());
  dateRange.value = null;
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  searchParams.pageSize = size;
  pagination.pageSize = size;
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  searchParams.pageIndex = page;
  pagination.pageIndex = page;
  loadData();
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  // 检查是否为永久封禁时间
  if (dateTime?.startsWith("9999-")) return "永久封禁";
  const date = new Date(dateTime);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped lang="less">
.block-list-container {
  padding: 20px;
  font-size: 16px; // 整体字号调整
  width: 100%;
  max-width: 100%;
  overflow-x: auto; // 添加横向滚动

  .search-card {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      font-size: 16px;
      font-weight: 500;
    }

    :deep(.el-input__inner) {
      font-size: 16px;
    }

    :deep(.el-select .el-input__inner) {
      font-size: 16px;
    }

    :deep(.el-button) {
      font-size: 16px;
      padding: 12px 20px;
    }
  }

  .table-card {
    width: 100%;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      font-weight: 600;

      .header-actions {
        display: flex;
        gap: 10px;

        .el-button {
          font-size: 16px;
          padding: 12px 20px;
        }
      }
    }

    :deep(.el-table) {
      font-size: 16px;
      width: 100% !important;
      min-width: 1070px; // 设置最小宽度，确保所有列都能显示

      .el-table__header {
        th {
          font-size: 16px;
          font-weight: 600;
          padding: 16px 8px;
        }
      }

      .el-table__body {
        td {
          font-size: 16px;
          padding: 16px 8px;
        }
      }

      .el-table__inner-wrapper {
        width: 100% !important;
      }

      .el-table__body-wrapper {
        width: 100% !important;
      }
    }

    :deep(.el-tag) {
      font-size: 14px;
      padding: 6px 12px;
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 6px;

    .clickable-avatar {
      cursor: pointer;
      transition: transform 0.2s ease;
      flex-shrink: 0;

      &:hover {
        transform: scale(1.1);
      }
    }

    .nickname {
      font-weight: 500;
      font-size: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;

    .el-button {
      margin: 0;
      flex-shrink: 0;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    :deep(.el-pagination) {
      font-size: 16px;

      .el-pagination__total {
        font-size: 16px;
      }

      .el-pagination__sizes {
        .el-select .el-input__inner {
          font-size: 16px;
        }
      }

      .btn-prev,
      .btn-next {
        font-size: 16px;
      }

      .el-pager li {
        font-size: 16px;
      }
    }
  }
}

// 全局样式，用于头像预览对话框
:global(.avatar-preview-dialog) {
  .el-message-box__content {
    padding: 20px;
  }

  .el-message-box__message {
    margin: 0;
  }
}
</style>
